<#
SQL 事务完整性检查（原生 PowerShell）
用途：扫描 file/sql/*.sql 是否包含成对的 BEGIN/COMMIT。
用法：
  pwsh -File scripts/windows/check-transaction.ps1
#>
param()

$WindowsDir = Split-Path -Parent $PSCommandPath
$ScriptsDir = Split-Path -Parent $WindowsDir
$RepoDir = Split-Path -Parent $ScriptsDir

$sqlDir = Join-Path $RepoDir 'file/sql'
if (!(Test-Path $sqlDir)) { Write-Error "缺少 SQL 目录：$sqlDir"; exit 2 }

$bad = @()
Get-ChildItem -Path $sqlDir -Recurse -File -Include *.sql | ForEach-Object {
  $txt = Get-Content -Raw $_.FullName
  $b = ([regex]::Matches($txt, '(?mi)\bBEGIN\b').Count)
  $c = ([regex]::Matches($txt, '(?mi)\bCOMMIT\b').Count)
  if ($b -lt 1 -or $c -lt 1) { $bad += $_.FullName }
}

if ($bad.Count -gt 0) {
  Write-Warning "以下 SQL 文件缺少完整事务："
  $bad | ForEach-Object { Write-Host " - $_" }
  exit 2
} else { Write-Host "SQL 事务完整性检查通过"; exit 0 }
